<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2024/5/10
 * Time: 15:55
 */

namespace app\zyhsapi\model;

use app\zyhsapi\model\comment\ZyhsArticleComment;
use app\zyhsapi\model\comment\ZyhsArticleCommentReply;
use think\Log;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsInteractiveMessage extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_interactive_message';
    protected $cacheModel = 'zyhs.interactive_message';

    public function saveData(array $data)
    {
        try
        {
            $id = $this->insertGetId([
                'atype' => $data['atype'],
                'type' => $data['type'],
                'aid' => $data['aid'],
                'comment_id' => $data['comment_id'],
                'reply_id' => $data['reply_id'],
                'uid' => $data['uid'],
                'uid1' => $data['uid1'],
                'res_id' => $data['res_id'],
                'create_time' => time(),
            ]);
            $this->listDataAdd($data['uid'], [$id => $id], $data['atype']);
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('has_unread', $data['atype'] . ':' . $data['uid'])->listAdd([$id => $id], 0, 'has_unread');
        }
        catch (\Exception $e)
        {
            Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
        return $id;
    }

    /**
     * 记录 点赞 互动消息 【只记录一次】
     * @param int $atype 1=>平行宇宙
     * @param int $aid
     * @param int $type 1=>文章点赞 5=>评论点赞 6=>回复点赞
     * @param int $uid 被点赞用户
     * @param int $uid1 点赞用户
     * @param int $commentId
     * @param int $crId
     * @return void
     */
    public function setZanInteractiveMessage(int $atype, int $aid, int $type, int $uid, int $uid1, int $commentId, int $crId = 0)
    {
        try
        {
            $num = $this->where(['uid1' => $uid1, 'atype' => $atype, 'aid' => $aid, 'type' => $type, 'comment_id' => $commentId, 'reply_id' => $crId])->count();

            if (!$num)
            {
                $id = $this->insertGetId([
                    'atype' => $atype,
                    'type' => $type,
                    'aid' => $aid,
                    'comment_id' => $commentId,
                    'reply_id' => $crId,
                    'uid' => $uid,      // 被点赞用户uid
                    'uid1' => $uid1,    // 点赞用户uid
                    'res_id' => 0,
                    'create_time' => time(),
                ]);
                $this->listDataAdd($uid, [$id => $id], $atype);
                CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('has_unread', $atype . ':' . $uid)->listAdd([$id => $id], 0, 'has_unread');
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
    }

    public function updateData($atype, $uid, $ids, $data)
    {
        try
        {
            $this->where(['id' => ['in', $ids]])->update($data);
            foreach ($ids as $id)
            {
                CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
                if (isset($data['delete_time']))
                {
                    $this->listDataDel($uid, [$id], $atype);
                }
                if (isset($data['read_time']))
                {
                    CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('has_unread', $atype . ':' . $uid)->delJudge([$id], 'has_unread');
                }
            }
        }
        catch (\Exception $e)
        {
            Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
        return true;
    }


    /**
     * 获取用户未读的消息ids
     * @param $atype 1=>平行宇宙
     * @param $uid
     * @return array|mixed
     * @throws \Exception
     */
    public function unreadMsgIds($atype, $uid)
    {
        return CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $atype . ':' . $uid)->setCacheKeyDetail('has_unread', $atype . ':' . $uid)->setSort('DESC')->ZsGetIocData('has_unread', function () use ($atype, $uid)
        {
            $where = ['read_time' => 0, 'uid' => $uid, 'atype' => $atype];
            try
            {
                $ids = $this->where($where)->column('id');
                if ($ids)
                {
                    return array_flip_key_value($ids);
                } else
                {
                    return [0 => 0];
                }
            }
            catch (\Exception $e)
            {
                return [];
            }
        });
    }

    /**
     * 获取不同消息类型的提示语
     * @param $data
     * @return string[]
     * @throws \Exception
     */
    public function getTypeInfo($data)
    {
        //1=>文章点赞 2=>文章评论 3=>回复【评论】 4=>回复【评论回复】 5=>评论点赞 6=>回复点赞
        $question = (new ZyhsPxyzUserQuestion())->getInfoById($data['aid'], ['content', 'status', 'uid', 'nickname', 'avatar_id']);
        $target = 'local';
        $link = "community_detail?id={$data['aid']}&comment_id={$data['comment_id']}&need_auth=2";
        switch ($data['type'])
        {
            case 1:
                $tip = '给了你鼓励';
                $content = '';
                $contentTip = '我的发布：' . $question['content'];
                if (!$question['status'])
                {
                    $target = 'toast';
                    $link = '该内容不存在';
                }
                break;
            case 2:
                $comment = (new ZyhsArticleComment())->getInfoById($data['res_id'], ['content', 'status']);
                $tip = '评论了我的发布';
                $content = $comment['content'];
                $contentTip = '我的发布：' . $question['content'];
                if (!$question['status'])
                {
                    $target = 'toast';
                    $link = '该内容不存在';
                }
                break;
            case 3:
                $comment = (new ZyhsArticleComment())->getInfoById($data['comment_id'], ['content', 'status']);
                $reply = (new ZyhsArticleCommentReply())->getInfoById($data['res_id'], ['content', 'status']);
                $tip = '回复了我的评论';
                $content = $reply['content'];
                $contentTip = '我的评论：' . $comment['content'];
                if (!$question['status'] || !$comment['status'])
                {
                    $target = 'toast';
                    $link = '该内容不存在';
                }
                break;
            case 4:
                $comment = (new ZyhsArticleComment())->getInfoById($data['comment_id'], ['content', 'status']);
                $reply = (new ZyhsArticleCommentReply())->getInfoById($data['reply_id'], ['content', 'status']);
                $reply2 = (new ZyhsArticleCommentReply())->getInfoById($data['res_id'], ['content', 'status']);
                $tip = '回复了我的评论';
                $content = $reply2['content'];
                $contentTip = '我的评论：' . $reply['content'];
                if (!$question['status'] || !$comment['status'] || !$reply['status'])
                {
                    $target = 'toast';
                    $link = '该内容不存在';
                }
                break;
            case 5:
                $comment = (new ZyhsArticleComment())->getInfoById($data['comment_id'], ['content', 'status']);
                $tip = '给了你赞';
                $content = '';
                $contentTip = '我的评论：' . $comment['content'];
                if (!$question['status'] || !$comment['status'])
                {
                    $target = 'toast';
                    $link = '该内容不存在';
                }
                break;
            case 6:
                $tip = '给了你赞';
                $comment = (new ZyhsArticleComment())->getInfoById($data['comment_id'], ['content', 'status']);
                $reply = (new ZyhsArticleCommentReply())->getInfoById($data['reply_id'], ['content', 'status']);
                $content = '';
                $contentTip = '我的评论：' . $reply['content'];
                if (!$question['status'] || !$comment['status'] || !$reply['status'])
                {
                    $target = 'toast';
                    $link = '该内容不存在';
                }
                break;
        }

        $userBindAstrInfo = (new ZyhsAstrBindUser())->getAstrBindUserData();
        $astrId = $userBindAstrInfo[$data['uid1']] ?? 0;
        if ($question['uid'] === $data['uid1'])
        {   // 本体
            $avatarNicknameConfig = config('pxyz');
            $nickname = $question['nickname'];
            $avatar = $avatarNicknameConfig['avatar_list'][$question['avatar_id']];
        } else
        {   // 其他 用户
            $userAvatarNicknameData = (new ZyhsArticleComment())->getUserAvatarNickname($data['uid1'], $userBindAstrInfo);
            $avatar = $userAvatarNicknameData['avatar'] ?? '';
            $nickname = $userAvatarNicknameData['nickname'] ?? '';
        }

        return [
            'tip' => $tip ?? '',
            'nickname' => $nickname,
            'avatar' => $avatar,
            'content' => $content ?? '',
            'content_tip' => $contentTip ?? '',
            'target' => $target,
            'link' => $link,
            'astr_id' => $astrId, //为0则说明不是咨询师回复内容 大于0则是咨询师回复内容
            'owner_tag' => $data['uid1'] === $question['uid'] ? '本体' : '', //是否是作者
        ];
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    public function dataInit(array $resData): array
    {
        foreach ($resData as $key => $itemData)
        {
            $resData[$key] = arrayKeyData2int($itemData, ['id', 'atype', 'aid', 'comment_id', 'reply_id', 'uid', 'uid1', 'res_id', 'create_time', 'read_time']);
        }
        return $resData;
    }

    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        if ($ids)
        {
            $where['id'] = ['in', $ids];
        } else
        {
            $where = ['uid' => $type[0], 'atype' => $type[1], 'delete_time' => 0];
        }
        return $this->where($where)->order('id desc')->column('*', 'id');
    }
}
